package com.lz.helper.face

import android.os.Handler
import android.util.Log
import java.lang.ref.SoftReference

/**
 * 只匹配单个, 证件照参数或者报名参数只能有一个为NULL
 */
class SingleRequest(
    private val type: Int,
    private val photoParams: FeatureParams?, //证件照
    private val examParams: FeatureParams?, //报名照
    private val handler: Handler,
    callback: FeatureRequest.Callback?
) : FeatureRequest {

    companion object {
        const val TAG = "SingleRequest"
    }

    private var reference = SoftReference(callback)

    override fun recognize(nvData: ByteArray, nvFeature: FloatArray, w: Int, h: Int): Int {
        if (examParams != null) {
            //校验报名照
            val detect = examParams.detect()
            if (detect == null || detect.size <= 1) {
                Log.d(TAG, "examParams callback detect err...")
                handler.post { reference.get()?.onFeatureError(type, ERR_DETECT) }
                return 1
            }
            val feature = examParams.feature()
            if (feature == null || feature.isEmpty()) {
                Log.d(TAG, "examParams callback feature1 err...")
                handler.post { reference.get()?.onFeatureError(type, ERR_FEATURE) }
                return 2
            }
            val res = float2Double(distance(nvFeature, feature))
            Log.d(TAG, "examParams feature res =  $res")
            if (res >= examParams.threshold) {
                val nvDataCopy = ByteArray(nvData.size)
                System.arraycopy(nvData, 0, nvDataCopy, 0, nvData.size)
                examParams.thresholdResult = res
                handler.post {
                    reference.get()?.onFeatureSuccess(type, nvDataCopy, w, h, null, examParams)
                }
                return 0
            }
        } else if (photoParams != null) {
            val detect = photoParams.detect()
            if (detect == null || detect.size <= 1) {
                Log.d(TAG, "photoParams detect err...")
                return -1
            }
            val feature = photoParams.feature()
            if (feature == null || feature.isEmpty()) {
                Log.d(TAG, "photoParams feature err...")
                return -1
            }
            val res = float2Double(distance(nvFeature, feature))
            Log.d(TAG, "photoParams feature2 res =  $res")
            if (res >= photoParams.threshold) {
                val nvDataCopy = ByteArray(nvData.size)
                System.arraycopy(nvData, 0, nvDataCopy, 0, nvData.size)
                photoParams.thresholdResult = res
                handler.post {
                    reference.get()?.onFeatureSuccess(type, nvDataCopy, w, h, photoParams, null)
                }
                return 0
            }
        }
        return -1
    }

    override fun timeout() {
        Log.d(TAG, "------request timeout------")
        handler.post { reference.get()?.onFeatureError(type, ERR_TIMEOUT) }
    }
}